import requests
from datetime import datetime, timedelta
import json
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point

# 定义时间及输入base_url(网址)和params（参数）以及header（头文件）
def fetch_data(start_time, end_time, time_delta_label):
    base_url = "https://sqfb.slt.zj.gov.cn/rest/newList/getNewTotalRainList"
    params = {
        "areaFlag": "1",
        "sss": "金华市",
        "ssx": "兰溪市",
        "st": start_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "et": end_time.strftime("%Y-%m-%dT%H:%M:%S"),
        "ly": "",
        "max": "",
        "min": "0",
        "bool": "false",
        "bxdj": "1,2,3,4,5,",
        "zm": "",
        "type": "0",
        "lx": "QX,ME,SX,DS"
    }

    headers = {
        "User-Agent": "Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14"
    }
    # 读取网站数据
    response = requests.get(base_url, params=params, headers=headers,verify=False)
    response.encoding = "utf-8"

    # 读取雨量数据
    data = json.loads(response.text)

    # 把字典中所有列表合并
    merged_list = [value for value_list in data.values() for value in value_list]

    # 传递属性到DataFrame里        
    data1 = []
    for line in merged_list:
        data1.append(line)

    df = pd.DataFrame(data1)

    # 将时间段列添加到DataFrame中
    df['时间段'] = [time_delta_label] * len(df)

    return df

# 定义时间段
base_time = datetime(2024, 6, 19, 8, 0, 0)
time_deltas = {
    "1小时": timedelta(hours=1),
    "3小时": timedelta(hours=3),
    "6小时": timedelta(hours=6),
    "12小时": timedelta(hours=12),
    "24小时": timedelta(days=1),
    "72小时": timedelta(days=3),
    "7天": timedelta(days=7)
}

all_data = pd.DataFrame()

for label, delta in time_deltas.items():
    start_time = base_time - delta
    df = fetch_data(start_time, base_time, label)
    all_data = pd.concat([all_data, df], ignore_index=True)

# 合并相同zm的名字，并透视表格
pivoted_data = all_data.pivot_table(
    index=['zm', 'jd', 'wd'],
    columns='时间段',
    values='yl',
    aggfunc='first'
).reset_index()

# 将X,Y坐标单独提取赋值
x_values = pivoted_data["jd"]
y_values = pivoted_data["wd"]

# 建立GEODataFrame，zip()为内置函数目的为打包为元组
geometry = [Point(xy) for xy in zip(x_values, y_values)]
gdf = gpd.GeoDataFrame(pivoted_data, geometry=geometry)
gdf.set_crs(epsg=4326, inplace=True)

# 输出到excel表格里
excel_file = r"g:\2023工作\suan\combined_result.xlsx"
pivoted_data.to_excel(excel_file, sheet_name="雨量", startcol=0, index=False)

# 输出到GDB文件
gdb_path = r"g:\2023工作\suan\combined_result.gdb"
gdf.to_file(gdb_path, driver='OpenFileGDB', encoding='utf-8')

print("所有时间段数据合并输出完毕")
